package com.yami.shop.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.sun.jndi.toolkit.url.UrlUtil;
import com.yami.shop.bean.model.*;
import com.yami.shop.bean.pt.YxPtgl;
import com.yami.shop.bean.pt.YxPtsp;
import com.yami.shop.common.util.RedisUtil;
import com.yami.shop.common.util.SpringContextUtils;
import com.yami.shop.dao.AccessTokenMapper;
import com.yami.shop.service.*;
import io.micrometer.core.instrument.util.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Service
public class SendMessageToUserServiceImpl extends ServiceImpl<AccessTokenMapper,AccessToken> implements SendMessageToUserService {


    @Autowired
    private UserService userService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderSettlementService orderSettlementService;

    @Autowired
    private IYxPtspService yxPtspService;

    @Autowired
    private ProductService productService;


    @Override
    public String getToken(String appid, String appsecret) {
        // 先判断redis中是否存在
        String usertoken = RedisUtil.get("messageToken");
        if (StringUtils.isBlank(usertoken) == false) {
            // token还未过期，获取后直接返回，无需重新获取
            return usertoken;
        }
        //  token已过期或不存在，需重新获取
        RedisUtil.del("messageToken");

        //获取access_token
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
                "&appid=" + appid + "&secret=" + appsecret;
        String json = new  RestTemplate().getForObject(url, String.class);
        AccessToken accessToken = new Gson().fromJson(json, AccessToken.class);
        if(accessToken!=null) {
            RedisUtil.set("messageToken", accessToken.getAccess_token(), 1200);
        }
        return accessToken.getAccess_token();
    }

    @Override
    public void pushWxAdmin(Order order, OrderSettlement orderSettlement) {
        //order = orderService.getOrderByOrderNumber("1269076039187959808");
       // orderSettlement = orderSettlementService.getSettlementByPayNo("1269076039716442112");
        // 调用上面的方法，获取AccessToken，传入APPID，appsecret
        String wxAccessToken = getToken("wx77577c20c1aa61b1", "d3cd926f87052ac422a765a2c891d549");
        if (StringUtils.isBlank(wxAccessToken)) {
            return;
        }
        // 填入订单详情信息
        Map<String, Object> dataMap = new HashMap<>();
        JSONObject wxTemplateData1 = new JSONObject();
        wxTemplateData1.put("value", order.getOrderNumber());// 订单编号
        JSONObject wxTemplateData2 = new JSONObject();
        if(order.getProdName().length()<10) {
            wxTemplateData2.put("value", order.getProdName());//商品名称
        }else{
            //截取字符串
            wxTemplateData2.put("value", order.getProdName().substring(0,7)+"...");//商品名称
        }
        JSONObject wxTemplateData3 = new JSONObject();
        wxTemplateData3.put("value",1 ); // 商品数量
        JSONObject wxTemplateData4 = new JSONObject();
        wxTemplateData4.put("value", order.getActualTotal()); // 实际支付金额
        JSONObject wxTemplateData5 = new JSONObject();
        //格式化时间
        SimpleDateFormat myFmt1=new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        if(order.getPayTime()!=null) {
            wxTemplateData5.put("value", myFmt1.format(order.getPayTime())); // 下单时间
        }else{
            wxTemplateData5.put("value", myFmt1.format(new Date())); // 下单时间
        }
        JSONObject wxTemplateData7 = new JSONObject();
        dataMap.put("character_string6", wxTemplateData1);
        dataMap.put("thing1", wxTemplateData2);
        dataMap.put("number3", wxTemplateData3);
        dataMap.put("amount2", wxTemplateData4);
        dataMap.put("time4", wxTemplateData5);


        // 获取下单人的openID
        String userId = order.getUserId();
        String bizUserId = userService.getBizUserId(userId);
        String payNo = orderSettlement.getPayNo();
        wxProPushMessage(bizUserId, wxAccessToken, payNo, dataMap);


    }

    @Override
    public void wxProPushMessage(String touser, String accesstoken, String prepay_id, Object data) {
        StringBuilder requestUrl = new StringBuilder("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=");
        requestUrl.append(accesstoken);
        JSONObject json = new JSONObject();
        json.put("touser", touser);// 接收人的openid
        json.put("template_id", "DSBqUiIQXlRhxQVA0z4BitCU4hJMnzzdB-b2MRRcV_Y");//设置模板id
        json.put("miniprogram_state", "formal");// 设置formid
        json.put("data", data);// 设置模板消息内容
        json.put("page", "pages/orderList/orderList");// 跳转微信小程序页面路径（非必须）
        Map<String, Object> map = null;
        try {
            HttpClient client = HttpClientBuilder.create().build();//构建一个Client
            HttpPost post = new HttpPost(requestUrl.toString());//构建一个POST请求
            StringEntity s = new StringEntity(json.toString(), "UTF-8");
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json; charset=UTF-8");
            post.setEntity(s);//设置编码，不然模板内容会乱码
            HttpResponse response = client.execute(post);//提交POST请求
            HttpEntity result = response.getEntity();//拿到返回的HttpResponse的"实体"
            String content = EntityUtils.toString(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void pushNotSuccessPT(YxPtgl yxPtgl) {
        String wxAccessToken = getToken("wx77577c20c1aa61b1", "d3cd926f87052ac422a765a2c891d549");
        if (StringUtils.isBlank(wxAccessToken)) {
            return;
        }
        //获取拼团价格
        YxPtsp yxPtsp = yxPtspService.getYxPtspbyProdId(yxPtgl.getGoodsid());

        // 填入订单详情信息
        Map<String, Object> dataMap = new HashMap<>();
        JSONObject wxTemplateData1 = new JSONObject();
        if(yxPtgl.getGoodsname().length()<10) {
            wxTemplateData1.put("value", yxPtgl.getGoodsname());//商品名称
        }else{
            //截取字符串
            wxTemplateData1.put("value", yxPtgl.getGoodsname().substring(0,7)+"...");//商品名称
        }
        JSONObject wxTemplateData2 = new JSONObject();
        wxTemplateData2.put("value", yxPtsp.getPtj());//拼团价格
        JSONObject wxTemplateData3 = new JSONObject();
        wxTemplateData3.put("value", yxPtgl.getCtrs()); // 拼团人数
        JSONObject wxTemplateData4 = new JSONObject();
        wxTemplateData4.put("value", yxPtgl.getPtrs()); // 剩余人数
        JSONObject wxTemplateData5 = new JSONObject();
        //剩余时间
        DateTime leftDate = DateUtil.offsetHour(yxPtgl.getKtsjtime(),+24);
        SimpleDateFormat myFmt1=new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        System.out.println("剩余时间为"+leftDate);
        wxTemplateData5.put("value",myFmt1.format(leftDate)); // 剩余时间

        JSONObject wxTemplateData7 = new JSONObject();
        dataMap.put("thing1", wxTemplateData1);
        dataMap.put("amount2", wxTemplateData2);
        dataMap.put("number3", wxTemplateData3);
        dataMap.put("number4", wxTemplateData4);
        dataMap.put("time5", wxTemplateData5);


        // 获取下单人的openID
        String userId = yxPtgl.getPzid();
        String bizUserId = userService.getBizUserId(userId);
        PushNotSuccessPTMessage(bizUserId, wxAccessToken, dataMap,yxPtgl);
    }

    @Override
    public void PushNotSuccessPTMessage(String touser, String accesstoken, Object data,YxPtgl yxPtgl) {
        StringBuilder requestUrl = new StringBuilder("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=");
        requestUrl.append(accesstoken);
        Product product = productService.getProductByProdId(yxPtgl.getGoodsid());
        StringBuffer buffer = new StringBuffer("/pages/groupbuy/groupbuy");
        buffer.append("?scene=").append(yxPtgl.getPtglid()).append("-").append(yxPtgl.getGoodsid()).append("-").append(product.getShopId());
        JSONObject json = new JSONObject();
        json.put("touser", touser);// 接收人的openid
        json.put("template_id", "J7inoyAsEEWPXCYT7XwEiNSKi2gak6cfF4NdTMdLVwg");//设置模板id
        json.put("miniprogram_state", "formal");// 设置formid
        json.put("data", data);// 设置模板消息内容
        json.put("page", "pages/orderList/orderList");// 跳转微信小程序页面路径（非必须）
        System.out.print("接收人信息为"+buffer);
        Map<String, Object> map = null;
        try {
            HttpClient client = HttpClientBuilder.create().build();//构建一个Client
            HttpPost post = new HttpPost(requestUrl.toString());//构建一个POST请求
            StringEntity s = new StringEntity(json.toString(), "UTF-8");
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json; charset=UTF-8");
            post.setEntity(s);//设置编码，不然模板内容会乱码
            HttpResponse response = client.execute(post);//提交POST请求
            HttpEntity result = response.getEntity();//拿到返回的HttpResponse的"实体"
            String content = EntityUtils.toString(result);
            System.out.println(content+" ***xiaoyueyue123");//打印返回的消息
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
